from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse
from web.forms.wiki import WikiModelForm
from web import models
from django.views.decorators.csrf import csrf_exempt  # 给某个视图加csrf_exempt装饰器，通过csrf的校验
from utils.tencent.cos import upload_file
from utils.encrytion.encrypt import uid


def wiki(request, project_id):
    """
    展示 wiki文档首页
    :param request:
    :param project_id:
    :return:
    """
    wiki_id = request.GET.get('wiki_id')
    if wiki_id and not wiki_id.isdecimal():
        return redirect('wiki')
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """
    在当前项目中增加 wiki文档
    :param request:
    :param project_id:
    :return:
    """
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'wiki_change.html', {'form': form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 判断用户是否已经选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    return render(request, 'wiki_change.html', {'form': form})


def wiki_del(request, project_id, wiki_id):
    """
    删除当前项目中 wiki文档
    :param request:
    :param project_id: 项目 id
    :return: wiki文档的 pk
    """
    url = reverse('wiki', kwargs={'project_id': project_id})
    models.Wiki.objects.filter(id=wiki_id, project_id=project_id).delete()
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    """
    编辑当前项目中的 wiki文档
    :param request:
    :param project_id: 项目 id
    :param wiki_pk: wiki文档的 pk
    :return:
    """
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    url = reverse('wiki', kwargs={'project_id': project_id})
    if not wiki_object:
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_change.html', {'form': form, 'wiki_id': wiki_id})

    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        # 判断用户是否已经选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        # 1 / wiki /?wiki_id = 1
        preview_url = f"{url}?wiki_id={wiki_id}"
        return redirect(preview_url)

    return render(request, 'wiki_change.html', {'form': form, 'wiki_id': wiki_id})


def wiki_catalog(request, project_id):
    """
    展示当前项目的所有文档的多级目录
    :param request:
    :return:
    """
    # 获取到queryset类型的wiki文档目录
    # 注意：json 不能序列化queryset类型的数据，故需要将其转化为列表形式
    data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id').order_by(
        'depth', 'id')

    return JsonResponse({'status': True, 'data': list(data)})


@csrf_exempt
# 套用csrf_exempt此装饰器，可以避免csrf校验
def wiki_upload(request, project_id):
    """
    使用markdown上传图片的插件
    :param request:
    :param project_id:
    :return:
    """
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = '文件不存在！'
        return JsonResponse(result)
    ext = image_object.name.rsplit('.')[-1]  # 取到图片的后缀名
    key = f"{uid(request.tracer.user.mobile_phone)}.{ext}"
    image_url = upload_file(
        request.tracer.project.bucket,
        request.tracer.project.region,
        image_object,
        key
    )
    result['success'] = 1
    result['url'] = image_url
    return JsonResponse(result)

